package com.duoqin.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.support.v7.widget.AppCompatTextView;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;

public class AutoFitTextView extends AppCompatTextView {
    private static final String TAG = "AutoFitTextView";

    private static final int TEXT_SIZE_STEP = 1;
    private int mMaxTextSize;
    private int mMinTextSize;
    private boolean mAutoEnabled = true;

    public AutoFitTextView(Context context) {
        super(context);
        setup(context);
    }

    public AutoFitTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setup(context);
    }

    public AutoFitTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setup(context);
    }

    public void noAutoFit() {
        mAutoEnabled = false;
    }

    private void setup(Context context) {
        mMaxTextSize = context.getResources().getDimensionPixelSize(R.dimen.duoqin_text_size_medium);
        mMinTextSize = context.getResources().getDimensionPixelSize(R.dimen.duoqin_text_size_smallest);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Log.d(TAG, "onDraw");
        if (!mAutoEnabled) {
            return;
        }
        int width = getWidth() - getPaddingLeft() - getPaddingRight();
        float originalTextSize = getTextSize();
        if (originalTextSize < mMinTextSize) {
            originalTextSize = mMaxTextSize;
        }
        String text = (String) getText();
        if (text == null || text.isEmpty()) {
            return;
        }
        int textLength;
        float textSize = originalTextSize;
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        for ( ; ;) {
            paint.setTextSize(textSize);
            textLength = paint.breakText(text, true, width, null);
            if (textLength < text.length() && textSize > mMinTextSize) {
                textSize -= TEXT_SIZE_STEP;
            } else {
                break;
            }
        }
        if (textSize != originalTextSize) {
            Log.d(TAG, "setTextSize, text size is " + textSize);
            setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
        }
    }

}
